package com.zsyh.changshang.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zsyh.changshang.MainActivity;
import com.zsyh.changshang.R;
import com.zsyh.changshang.basic.BaseActivity;
import com.zsyh.changshang.basic.MyAppliaction;
import com.zsyh.changshang.basic.PhoneContract;
import com.zsyh.changshang.basic.PhonePresenter;
import com.zsyh.changshang.basic.RetrofitHelper;
import com.zsyh.changshang.basic.StatusUtil;
import com.zsyh.changshang.basic.Viewable;
import com.zsyh.changshang.bean.LoginBean;
import com.zsyh.changshang.bean.PrivicesBean;
import com.zsyh.changshang.data.DataApi;
import com.zsyh.changshang.util.EmptyUtil;
import com.zsyh.changshang.util.SPUtils;
import com.zsyh.changshang.util.TimeTextLogin;
import com.zsyh.changshang.util.ToastUtil;
import com.zsyh.changshang.weight.DialogManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;


@Viewable(presenter = PhonePresenter.class, layout = R.layout.loginlayout)
public class LoginActivity extends BaseActivity<PhoneContract.View, PhoneContract.Presenter> implements PhoneContract.View {
    @BindView(R.id.image_dl)
    ImageView imageDl;
    @BindView(R.id.tv_ap)
    TextView tvAp;
    @BindView(R.id.denglu)
    TextView denglu;
    @BindView(R.id.zhuce)
    TextView zhuce;
    @BindView(R.id.image_p)
    ImageView imageP;
    @BindView(R.id.myphone)
    EditText myphone;
    @BindView(R.id.re_phone)
    RelativeLayout rePhone;
    @BindView(R.id.xian)
    View xian;
    @BindView(R.id.image_yzm)
    ImageView imageYzm;
    @BindView(R.id.btn_get_code)
    Button btnGetCode;
    @BindView(R.id.myyzm)
    EditText myyzm;
    @BindView(R.id.re_mima)
    RelativeLayout reMima;
    @BindView(R.id.xianyi)
    View xianyi;
    @BindView(R.id.login)
    Button login;
    @BindView(R.id.redenglu)
    RelativeLayout redenglu;
    @BindView(R.id.image_pzhuce)
    ImageView imagePzhuce;
    @BindView(R.id.zhucephone)
    EditText zhucephone;
    @BindView(R.id.rezhuce_phone)
    RelativeLayout rezhucePhone;
    @BindView(R.id.xianzhuxe)
    View xianzhuxe;
    @BindView(R.id.image_yzmzhuce)
    ImageView imageYzmzhuce;
    @BindView(R.id.btn_get_codezhuce)
    Button btnGetCodezhuce;
    @BindView(R.id.myzhuceyzm)
    EditText myzhuceyzm;
    @BindView(R.id.re_zhucemima)
    RelativeLayout reZhucemima;
    @BindView(R.id.xianyizhuce)
    View xianyizhuce;
    @BindView(R.id.check)
    CheckBox check;
    @BindView(R.id.woyiyuedu)
    TextView woyiyuedu;
    @BindView(R.id.xieyi)
    TextView xieyi;
    @BindView(R.id.zhuceanniu)
    Button zhuceanniu;
    @BindView(R.id.rezhuce)
    RelativeLayout rezhuce;
    private TimeTextLogin mTimeText;

    private DataApi dataApi;
    private DialogManager mDialogManager;
    private String type;
    @Override
    public void init() {

        StatusUtil.setUseStatusBarColor(this, Color.parseColor("#00000000"));
        StatusUtil.setSystemStatus(this, true, true);
        redenglu.setVisibility(View.VISIBLE);
        rezhuce.setVisibility(View.GONE);
        denglu.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
        zhuce.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
        dataApi = RetrofitHelper.getInstance().getRetrofit().create(DataApi.class);
        mDialogManager=new DialogManager();

    }



    @SuppressLint("ResourceAsColor")
    @OnClick({R.id.denglu, R.id.zhuce, R.id.btn_get_codezhuce, R.id.check, R.id.woyiyuedu, R.id.xieyi, R.id.zhuceanniu,R.id.login,R.id.btn_get_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.denglu:
                redenglu.setVisibility(View.VISIBLE);
                rezhuce.setVisibility(View.GONE);
                denglu.setTextColor(getResources().getColor(R.color.dengluzhifang));
                zhuce.setTextColor(getResources().getColor(R.color.budianjihui));
                denglu.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
                zhuce.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
                break;
            case R.id.zhuce:
                redenglu.setVisibility(View.GONE);
                rezhuce.setVisibility(View.VISIBLE);
                denglu.setTextColor(getResources().getColor(R.color.budianjihui));
                zhuce.setTextColor(getResources().getColor(R.color.dengluzhifang));
                denglu.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
                zhuce.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
                break;

            case R.id.btn_get_code:
                type="1";
                if (TextUtils.isEmpty(myphone.getText().toString())) {
                    Toast.makeText(this, "手机号码不能为空", Toast.LENGTH_LONG).show();
                    return;
                }else{
                    if(isPhoneNumber(myphone.getText().toString())){
                        getYzm(myphone.getText().toString());
                    }else{
                        Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
                    }

                }
                break;
            case R.id.btn_get_codezhuce:
                type="2";
                if (TextUtils.isEmpty(zhucephone.getText().toString())) {
                    Toast.makeText(this, "手机号码不能为空", Toast.LENGTH_LONG).show();
                    return;
                }else{
                    if(isPhoneNumber(zhucephone.getText().toString())){
                        getYzm(zhucephone.getText().toString());
                    }else{
                        Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
                    }

                }

                break;
            case R.id.check:

                break;
            case R.id.woyiyuedu:

                break;
            case R.id.xieyi:

                break;
            case R.id.zhuceanniu:
                if (EmptyUtil.isEmpty(zhucephone.getText().toString())) {
                ToastUtil.showS(MyAppliaction.getContext(), "请输入手机号");
                return;
            }else {
                if(isPhoneNumber(zhucephone.getText().toString())==false){
                    ToastUtil.showS(MyAppliaction.getContext(), "请填写正确的手机号码");
                    return;
                }
            }

                if (EmptyUtil.isEmpty(myzhuceyzm.getText().toString())) {
                    ToastUtil.showS(MyAppliaction.getContext(), "请输入验证码");
                    return;
                }

                if(check.isChecked()==false){
                    ToastUtil.showS(MyAppliaction.getContext(), "请阅读并同意用户协议");
                    return;
                }

                getzhuceyanzheng(zhucephone.getText().toString(),myzhuceyzm.getText().toString());
              /*  Intent intent=new Intent(this,RegisterActivity.class);
                startActivity(intent);
*/
                break;

            case R.id.login:

                if (EmptyUtil.isEmpty(myphone.getText().toString())) {
                    ToastUtil.showS(MyAppliaction.getContext(), "请输入手机号");
                    return;
                }else {
                    if(isPhoneNumber(myphone.getText().toString())==false){
                        ToastUtil.showS(MyAppliaction.getContext(), "请填写正确的手机号码");
                        return;
                    }
                }

                if (EmptyUtil.isEmpty(myyzm.getText().toString())) {
                    ToastUtil.showS(MyAppliaction.getContext(), "请输入验证码");
                    return;
                }

                Login(myphone.getText().toString(),myyzm.getText().toString());

                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        redenglu.setVisibility(View.VISIBLE);
        rezhuce.setVisibility(View.GONE);
        denglu.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
        zhuce.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
        myzhuceyzm.setText("");
        zhucephone.setText("");


    }

    /**
     * 注册验证
     */
    public void getzhuceyanzheng(String phone,String yzm){
        mDialogManager.showLoadingDialogFragment(getSupportFragmentManager());
        dataApi = RetrofitHelper.getInstance().getRetrofit().create(DataApi.class);
        dataApi.Yanzmengregist(phone,yzm)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String body=responseBody.string();
                            JSONObject jsonObject=new JSONObject(body);
                            if(jsonObject.getString("errorCode").equals("0")){
                                Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
                                startActivity(intent);
                            }else{
                                ToastUtil.showS(MyAppliaction.getContext(),jsonObject.getString("msg"));
                            }
                            mDialogManager.hideLoadingDialogFragment();
                            Log.e("yanzheng",body+"");
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    public void onError(Throwable e) {
                        mDialogManager.hideLoadingDialogFragment();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public void getYzm(String phone) {
        dataApi.Yzm(phone)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String body = responseBody.string();
                            Log.e("yzm", body);
                            JSONObject jsonObject = new JSONObject(body);
                            String errorCode = jsonObject.getString("errorCode");
                            if (errorCode.equals("0")) {
                                if(type.equals("1")){
                                    mTimeText = new TimeTextLogin(60000, 1000, btnGetCode);
                                    mTimeText.start();
                                }else if(type.equals("2")){
                                    mTimeText = new TimeTextLogin(60000, 1000, btnGetCodezhuce);
                                    mTimeText.start();
                                }

                                //YZcode = jsonObject.getString("data");


                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("yzmerror", e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    public void Login(String phone,String yzm){
        mDialogManager.showLoadingDialogFragment(getSupportFragmentManager());
        dataApi = RetrofitHelper.getInstance().getRetrofit().create(DataApi.class);
        dataApi.Login(phone,yzm)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String body=responseBody.string();
                            mDialogManager.hideLoadingDialogFragment();
                            JSONObject jsonObject=new JSONObject(body);
                            if(jsonObject.getString("errorCode").equals("0")){
                               Gson gson=new Gson();
                                LoginBean loginBean=gson.fromJson(body,LoginBean.class);
                                SPUtils.put(LoginActivity.this,"token",(String)loginBean.getData().getToken().getToken());
                                ToastUtil.showS(MyAppliaction.getContext(), "登录成功");
                                Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                                startActivity(intent);
                                LoginActivity.this.finish();

                            }else{
                                ToastUtil.showS(MyAppliaction.getContext(),jsonObject.getString("msg"));
                            }

                            Log.e("denglu",body+"");
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    public void onError(Throwable e) {
                        mDialogManager.hideLoadingDialogFragment();
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }





}
